package jh.com.jhappbf.assay;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.AssaySettingModel;
import jh.com.jhappbf.utils.JsonHelper;

public class AssayQuery extends AbActivity {

    private View mContentView;
    private View mErrorView;
    private List<JSONObject> mData;
    private AbTitleBar mTitleBar;
    private AbPullToRefreshView mRefreshView; // 下拉刷新上拉加载更多
    private AbLoadDialogFragment mDialogFragment = null;
    private ListView mListView;
    private LinearLayout mTitleLayout;
    private Button mTryAgain;
    private int mCurrentPage = 0;
    private List<String> mHeaderContent;
    private Context mAppcontext;
    private MyAssayAdapter mAdapter;
    private int mCurrentScreenWidth;
    private AssaySettingModel mSettingModel;
    private Drawable mLeftDrawable;
    private final int mPageSize = 30;
    private final int UPDATEPRICE = 0X0001;
    private final int ADDPRICE = 0X0002;
    private final int GETSETTING = 0X0003;
    private List<JSONObject> mTemp;
    private Button mRightBtn;
    private String mStates = "0";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = getLayoutInflater().inflate(R.layout.assay_query, null);
        mErrorView = getLayoutInflater().inflate(R.layout.net_error_activity, null);
        mAppcontext = getApplicationContext();
        setAbContentView(mContentView);
        Intent i = getIntent();
        mSettingModel = i.getParcelableExtra("setting");
        mTitleBar = getTitleBar();
        mTitleBar.setTitleText("化验查询");
        mTitleBar.setLogo(R.drawable.button_selector_back);
//        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this,R.color.orange));;
        mTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this,R.color.orange));
        mTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mTitleBar.setLogoLine(R.mipmap.line);
        init();
    }

    /**
     * 根据列数获取列宽
     *
     * @param columnCount 列的个数
     * @return 平均列宽
     */
    private int getWidth(int columnCount) {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        return (metrics.widthPixels) / (columnCount * 2);
    }

    private void init() {
        mRefreshView = mContentView.findViewById(R.id.universal_pullToRefreshView);
        mListView = mContentView.findViewById(R.id.universal_listView);
        mTitleLayout = mContentView.findViewById(R.id.universal_title);
        mTryAgain = mErrorView.findViewById(R.id.network_error_btn);

        View v = getLayoutInflater().inflate(R.layout.title_right_app_btn_view, null);

        mRightBtn = v.findViewById(R.id.title_right_btn);
        mTitleBar.addRightView(v);
        mRightBtn.setOnClickListener(v1 -> {
            Intent i = new Intent(AssayQuery.this, AssaySelectSetting.class);
            i.putExtra("setting", mSettingModel);
            startActivityForResult(i, GETSETTING);
        });

        mCurrentScreenWidth = getWidth(4);
        mLeftDrawable = ContextCompat.getDrawable(this,R.mipmap.table_line);
        mLeftDrawable.setBounds(0, 0, mLeftDrawable.getMinimumWidth(), mLeftDrawable.getMinimumHeight());
        mData = new ArrayList<>();
        mTemp = new ArrayList<>();
        mHeaderContent = new ArrayList<>();
        mHeaderContent.add("序号");
        mHeaderContent.add("货名");
        mHeaderContent.add("单价");
        mHeaderContent.add("扣杂");
        mHeaderContent.add("扣水");
        mHeaderContent.add("日期");
        mHeaderContent.add("时间");
        mHeaderContent.add("操作员");
        mHeaderContent.add("image");
        mAdapter = new MyAssayAdapter();
        mListView.setAdapter(mAdapter);

        mListView.setOnItemLongClickListener((parent, view, position, id) -> {
            PopupMenu menu = new PopupMenu(AssayQuery.this, view);


//					getMenuInflater().inflate(R.menu.price_manager,
//							menu.getMenu());

            getMenuInflater().inflate(R.menu.assayquery, menu.getMenu());
            menu.setOnMenuItemClickListener(item -> {
                switch (item.getItemId()) {
                    case R.id.assay_query_menu_item:
                        //		updatePrice(position);
                        JSONObject obj = mData.get(position);
                        String id1 = obj.optString("编号");
                        Intent intent = new Intent(AssayQuery.this, ShowAssayImgActivity.class);
                        intent.putExtra("id", id1);
                        startActivity(intent);


                        break;
                    case R.id.price_delete_menu_item:
                        //		deletePrice(position);
                        break;
                    case R.id.price_stop_menu_item:
                        //		stopOrStartPrice(position,"1");
                        break;
                    case R.id.price_start_menu_item:
                        //		stopOrStartPrice(position,"0");
                        break;
                    default:
                        break;
                }
                return true;
            });
            menu.show();
            return true;
        });


        mRefreshView.setOnHeaderRefreshListener(arg0 -> loadFirst());

        mRefreshView.setOnFooterLoadListener(arg0 -> loadMoreTask());
        loadFirst();
    }

    /**
     * 第一次加载
     */
    private void loadFirst() {
        mDialogFragment = AbDialogUtil.showLoadDialog(AssayQuery.this,
                R.mipmap.ic_load, "加载中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> {
            mContentView.setVisibility(View.VISIBLE);
            refreshTask();
        });
    }

    /**
     * 上拉加载更多
     */
    private void loadMoreTask() {
        String methodName = "queryAllAssay";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("currentPageStr");
        param.add("pageSizeStr");
        param.add("startTime");
        param.add("endTime");
        //	param.add("spec");
        param.add("cargoname");
        //	param.add("sender");
        //	param.add("receiver");
        //	param.add("states");

        value.add(String.valueOf(mCurrentPage));
        value.add(String.valueOf(mPageSize));
        if (mSettingModel == null) {
//            Date date = new Date();
            String end = "";
            String start = "";
            value.add(start);
            value.add(end);
            value.add("");
//			value.add("");
//			value.add("");
//			value.add("");
//			value.add("0");

        } else {
            value.add(mSettingModel.getStartTime());
            value.add(mSettingModel.getEndTime());
            //value.add(mSettingModel.getSpec());
            value.add(mSettingModel.getCargoname());
            //value.add(mSettingModel.getSender());
            //value.add(mSettingModel.getReceiver());
            //	mStates = mSettingModel.getStates();
            //	value.add(mStates);
        }

        Listener<String> listener = response -> {
            mRefreshView.onFooterLoadFinish();
            if (mTemp != null && mTemp.size() < mPageSize) {
                mData.removeAll(mTemp);
                mTemp.clear();
            }
            mTemp = JsonHelper.getJsonObjects(response);
            if (mTemp != null && mTemp.size() > 0) {
                mData.addAll(mTemp);
                mAdapter.notifyDataSetChanged();
                if (mTemp.size() == mPageSize) {
                    mCurrentPage++;
                }
            }
        };

        ErrorListener errorListener = error -> {
            mRefreshView.onFooterLoadFinish();
            setAbContentView(mErrorView);
            AbToastUtil.showToast(mAppcontext, "数据加载失败！");
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppcontext).addRequest(webService);
    }

    /**
     * 下拉刷新
     */
    private void refreshTask() {

        String methodName = "queryAllAssay";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("currentPageStr");
        param.add("pageSizeStr");
        param.add("startTime");
        param.add("endTime");
        //	param.add("price");
        param.add("cargoname");
//		param.add("kouza");
//		param.add("koushui");
        //param.add("states");

        value.add("1");
        value.add(String.valueOf(mPageSize));
        if (mSettingModel == null) {
//            Date date = new Date();
            String end = "";
            String start = "";
            value.add(start);
            value.add(end);
            value.add("");
//			value.add("");
//			value.add("");
//			value.add("");
//			value.add("0");

        } else {
            value.add(mSettingModel.getStartTime());
            value.add(mSettingModel.getEndTime());
//			value.add(mSettingModel.getSpec());
            value.add(mSettingModel.getCargoname());
//			value.add(mSettingModel.getSender());
//			value.add(mSettingModel.getReceiver());
//			mStates = mSettingModel.getStates();
//			value.add(mStates);
        }

//        Log.e("wwh", param.toString());
  //      Log.e("wwh", value.toString());


        Listener<String> listener = response -> {

//               Log.e("wwh", response);

            AbDialogUtil.removeDialog(AssayQuery.this);
            mRefreshView.onHeaderRefreshFinish();
            List<JSONObject> newListData = JsonHelper
                    .getJsonObjects(response);
            if (newListData != null) {
                mData.clear();
                mData.addAll(newListData);
                if (newListData.size() == mPageSize) {
                    mCurrentPage++;
                }
                if (newListData.size() > 0) {
                    getHeaderTitle(newListData.get(0));
                }
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(AssayQuery.this);
            mRefreshView.onHeaderRefreshFinish();
            setAbContentView(mErrorView);
            mAdapter.notifyDataSetChanged();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppcontext).addRequest(webService);
    }


    /**
     * 获取表头
     *
     */
    private void getHeaderTitle(JSONObject obj) {
        String[] alias = obj.optString("alias").split(",");
        if (alias.length > 0) {
            mHeaderContent.clear();
            for (String item : alias) {
                if (!"image1".equals(item)) {
                    mHeaderContent.add(item);
                }
            }
        }

//        Log.e("wwh", alias.toString());

        makeHeader();
    }

    /**
     * 制作表头
     */
    private void makeHeader() {
        mTitleLayout.removeAllViews();
        TableLayout table = new TableLayout(mAppcontext);
        TableRow row = new TableRow(mAppcontext);
        for (int index = 0; index < mHeaderContent.size(); index++) {
            TextView txt = new TextView(AssayQuery.this);
            switch (mHeaderContent.get(index)) {
                case "序号":
                case "货名":
                case "单价":
                case "扣杂":
                case "扣水":
                case "操作员":
                case "车号":
                case "化验人":
                case "编号":
                case "收货":
                    txt.setWidth((int) (mCurrentScreenWidth * 2.5));
                    break;

                //隐藏规格列
                case "规格":
                    txt.setWidth(0);
                    break;
                case "化验时间":
                case "日期":
                    txt.setWidth(mCurrentScreenWidth * 3);
                    break;
                case "剩余金额":
                case "发货":
                    txt.setWidth((int) (mCurrentScreenWidth * 1.5));
                    break;
                default:
                    txt.setWidth(mCurrentScreenWidth);
                    break;
            }
            txt.setTextColor(Color.BLACK);
            txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            txt.setGravity(Gravity.CENTER);
            txt.setPadding(1, 10, 0, 10);
            txt.setId(index);
            txt.setText(mHeaderContent.get(index));
            txt.setCompoundDrawables(mLeftDrawable, null, null, null);
            row.addView(txt);
        }
        table.addView(row);
        mTitleLayout.addView(table);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UPDATEPRICE && resultCode == RESULT_OK) {
            loadFirst();
        } else if (requestCode == ADDPRICE && resultCode == RESULT_OK) {
            loadFirst();
        } else if (data != null && requestCode == GETSETTING) {
            mSettingModel = data.getParcelableExtra("result");
            loadFirst();
        }
    }

    private class MyAssayAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("NewApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            TableLayout tableLayout;

            if (convertView == null) {
                tableLayout = new TableLayout(AssayQuery.this);
                TableRow tableRow = new TableRow(AssayQuery.this);
                Drawable mItemSelect = ContextCompat.getDrawable(AssayQuery.this,R.drawable.list_item_bg);
                tableRow.setBackground(mItemSelect);
                tableRow.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);

                for (int index = 0; index < mHeaderContent.size(); index++) {
                    TextView txt = new TextView(AssayQuery.this);
                    switch (mHeaderContent.get(index)) {
                        case "序号":
                        case "货名":
                        case "单价":
                        case "扣杂":
                        case "扣水":
                        case "操作员":
                        case "车号":
                        case "化验人":
                        case "编号":
                        case "收货":
                            txt.setWidth((int) (mCurrentScreenWidth * 2.5));
                            break;
                        //隐藏规格列 optimize dodgy
                        case "规格":
                            txt.setWidth(0);
                            break;
                        case "化验时间":
                        case "日期":
                            txt.setWidth(mCurrentScreenWidth * 3);
                            break;
                        case "剩余金额":
                        case "发货":
                            txt.setWidth((int) (mCurrentScreenWidth * 1.5));
                            break;
                        default:
                            txt.setWidth(mCurrentScreenWidth);
                            break;
                    }

                    txt.setTextColor(Color.BLACK);
                    txt.setGravity(Gravity.CENTER);
                    txt.setCompoundDrawables(mLeftDrawable, null, null, null);
                    txt.setPadding(1, 0, 1, 0);
                    txt.setId(index);
                    txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                    tableRow.addView(txt);
                }
                tableLayout.addView(tableRow);
                convertView = tableLayout;
                convertView.setTag(tableLayout);
            } else {
                tableLayout = (TableLayout) convertView.getTag();
            }

            JSONObject data = mData.get(position);
            String content;
            for (int index = 0; index < mHeaderContent.size(); index++) {
                View view = tableLayout.getChildAt(0).findViewById(index);
                if (view instanceof TextView) {
                    TextView txt = (TextView) view;
                    content = data.optString(mHeaderContent.get(index));
                    if ("null".equalsIgnoreCase(content)) {
                        content = "";
                    }
                    txt.setText(content);

                }
            }

            return convertView;
        }
    }
}
